package com.dqyt.khjc.service;

import com.alibaba.fastjson.JSON;
import com.dqyt.app.bean.Report;
import com.dqyt.app.bean.Sample;
import com.dqyt.app.bean.WorkBean;
import com.dqyt.app.mongo.ReportDao;
import com.dqyt.app.mongo.SampleDao;
import com.dqyt.common.check.CheckTool;
import com.dqyt.common.constant.AuthorityID;
import com.dqyt.common.constant.Constant;
import com.dqyt.common.constant.Opt;
import com.dqyt.common.utils.BHUtil;
import com.dqyt.common.utils.StringUtil;
import com.dqyt.common.utils.UserInfoUtil;
import com.dqyt.khjc.bean.*;
import com.dqyt.khjc.config.Config;
import com.dqyt.khjc.mapper.*;
import com.dqyt.khjc.mongo.WorkDao;
import com.dqyt.khjc.swicth.SwitchConfig;
import com.dqyt.khjc.utils.IpUtil;
import com.dqyt.khjc.utils.TimeUtil;
import com.google.gson.annotations.JsonAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 样品信息 pc端使用
 */
@Service
public class SamplePcService {

    @Autowired
    private SampleDao mSampleDao;

    @Autowired
    private QrCodeMapper qrCodeMapper;

    @Autowired
    private HistoryMapper historyMapper;

    @Autowired
    private WorkDao mWorkDao;

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ManufacturerMapper manufacturerMapper;


    @Autowired
    private ReportDao reportDao;


    @Autowired
    private WorkMapper workMapper;


    /**
     * 查询样品
     * @param request
     * @param type  类型
     * @param sbbh 设备编号
     * @param bsbh  标识编号
     * @param erweima  二维码
     * @return
     */
    public ResultMsg getPcSample(HttpServletRequest request, int type,String sbbh, String bsbh, String erweima){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_SJYPDJ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            //数据验证
            if (type == 0 || sbbh=="" || bsbh =="") {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }

            //通过标识编号去查询
            Sample sample33 =   mSampleDao.getPcSampleByBsbh(bsbh);
            if(null != sample33){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("该标识编号已经被使用了");
                return ret;
            }
            ret.setCode(ResultMsg.NEW_SAMPLE_FP);

//            Sample sample = new Sample(); // 新建数据
//            sample.type = type;
//            sample.erweima = BHUtil.getErWeiMa(type,sbbh, bsbh);
//            sample.bsbhHrader = BHUtil.getbsbhHrade(bsbh,type);
//            ret.setData(sample);


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 查询样品
     * @param request
     * @param type  类型
     * @param sbbh 设备编号
     * @param bsbh  标识编号
     * @param erweima  二维码
     * @return
     */
    public ResultMsg getPcSample2(HttpServletRequest request, int type,String sbbh, String bsbh, String erweima){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_SJYPDJ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            //数据验证
            if (type == 0) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }


            // 取得条件数据
            List<Sample> samples = mSampleDao.getSample(type,sbbh, bsbh, erweima);
            Sample sample = null;
            if(samples.size()>0){
                sample = samples.get(0); // 取得数据
                //在根据旧的数据吧二维码查询出来
                QrCodeBean qrCodeBean =  qrCodeMapper.getQrCodeBySbbh(sample.sbbh);
                if(null !=qrCodeBean){
                    sample.erweima =qrCodeBean.getErweima();
                    if( sample.type == 1){//如果是呼吸器
                        sample.respirator.erweima = qrCodeBean.getErweima();
                    }else{
                        sample.cylinders.erweima = qrCodeBean.getErweima();
                    }
                    ret.setCode(ResultMsg.OLD_SAMPLE); // 旧的数据
                    ret.setData(sample);
                }else{
                    ret.setCode(ResultMsg.ERROR); // 旧的数据
                    ret.setMsg("二维码生成异常，请刷新重试");
                }
            }else{ //如果数据不存在
                //就创建二维码 并将二维码保存到本地
                ret.setCode(ResultMsg.NEW_SAMPLE_FP);
                sample = new Sample(); // 新建数据
                sample.type = type;
                sample.erweima = BHUtil.getErWeiMa(type,sbbh);
                ret.setData(sample);
                QrCodeBean qrCodeBean =null;
                qrCodeBean =  qrCodeMapper.getQrCodeBySbbh(sbbh);
                if(qrCodeBean == null){
                    qrCodeBean = new QrCodeBean();
                    //将二维码放到数据库
                    qrCodeBean.setSbbh(sbbh);
                    qrCodeBean.setErweima(sample.erweima);
                    long nowTime = TimeUtil.getCurrentTimeMillis();
                    qrCodeBean.setAddTime(nowTime);
                    qrCodeBean.setAddUser(user.getUserId()+"");
                    qrCodeBean.setUpdateTime(nowTime);
                    qrCodeBean.setUpdateUser(user.getUserId()+"");
                    qrCodeMapper.saveQrCode(qrCodeBean);
                }
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }





    /**
     * 根据标识编号查询 样品信息
     * @param request
     * @param bsbh
     * @return
     */
    public ResultMsg  getPcSampleByBsbh(HttpServletRequest request,String bsbh){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {

            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_SJYPDJ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            Sample sample = mSampleDao.getPcSampleByBsbh(bsbh);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(sample);
            ret.setMsg("查询成功");
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 查询样品信息 根据id
     *
     * @param request
     * @param bsbh
     * @return
     */
    public ResultMsg getPcSampleBypr(HttpServletRequest request,String bsbh,String merweima){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_SJYPDJ) && !CheckTool.checkAuthority(user, AuthorityID.SBWX_XZSBWX)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            //将含有这个的替换 没有就不替换
            String erweima =   merweima.replace("DQYT：","DQYT:");

            // 取得条件数据
            List<Sample> samples = mSampleDao.getSamplebypr(bsbh,erweima);
            // 如果没有对应的数据
            if (samples == null || samples.size()==0) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("无此数据！");
                return ret;
            }else{
                Sample sample = samples.get(0);
                ret.setCode(ResultMsg.SUCESS); // 旧的数据
                ret.setData(sample);
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 新增样品信息
     * @param request
     * @param sampleJson
     * @return
     */
    public ResultMsg savePcSample(HttpServletRequest request,String sampleJson){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_SJYPDJ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            Sample sample = JSON.parseObject(sampleJson, Sample.class);
            sample.sbbh = sample.sbbh.trim();

            // 数据检查
            if (StringUtil.isEmpty(sample.bsbh) || StringUtil.isEmpty(sample.erweima)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据错误！");
                return ret;
            }
            //如果设备编号里面包含了二维码协议头
            if(sample.sbbh.indexOf(Constant.EWM_HEAD) != -1){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作！");
                return ret;
            }

            //设置上次检验日期
            //先查询最新的数据
            List<Sample> mmsmps =  mSampleDao.getSample(sample.type,sample.sbbh, "", "");
            if(null != mmsmps && mmsmps.size()>0){
                Sample oll = mmsmps.get(0);
                //如果是呼吸器
                if(sample.type == Sample.YP_TYPE_HXQ){
                    if(!sample.bsbh.equals(oll.bsbh)){
                        sample.respirator.scjyrq = oll.respirator.sjri;
                    }

                }else{//气瓶
                    if(!sample.bsbh.equals(oll.bsbh)){
                        sample.cylinders.scjyrq = oll.cylinders.sjri;
                    }
                }
            }

            //如果面罩对象不为空
            if(null != sample.respirator){
                //如果委托方Id为空就新建一条委托方的数据
                if(0 == sample.respirator.wtfId || "".equals(sample.respirator.wtfId)){
                    CustomerBean customerBean = new CustomerBean();
                    customerBean.setEnterpriseName(sample.respirator.wtf);
                    customerBean.setProvince(0);
                    customerBean.setCity(0);
                    customerBean.setBlock(0);
                    customerBean.setAddress("");
                    customerBean.setContacts("");
                    customerBean.setPhone("");
                    customerBean.setEmail("");
                    customerBean.setTelephone("");
                    customerBean.setFax("");

                    customerBean.setAddTime(TimeUtil.currentTimeMillis());
                    customerBean.setAddUser(String.valueOf(user.getUserId()));
                    customerBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    customerBean.setUpdateUser(String.valueOf(user.getUserId()));
                    int res = customerMapper.addCustomer(customerBean);
                    sample.wtfId = customerBean.getCustomerId();
                    sample.sjr = sample.respirator.sjr;
                }else{
                    sample.wtfId = sample.respirator.wtfId;
                    sample.sjr = sample.respirator.sjr;
                    sample.sjrId =sample.respirator.sjrId;
                }

                //如果制造厂商的id为空  就新增一条信息
                if(null ==sample.respirator.zzcsId|| "".equals(sample.respirator.zzcsId)){
                    ManufacturerBean manufacturerBean = new ManufacturerBean();
                    manufacturerBean.setName(sample.respirator.zzcs);
                    manufacturerBean.setAddress("");
                    long tt =TimeUtil.currentTimeMillis();
                    manufacturerBean.setAddTime(tt);
                    manufacturerBean.setAddUser(user.getUserId()+"");
                    manufacturerBean.setUpdateTime(tt);
                    manufacturerBean.setUpdateUser(user.getUserId()+"");
                    //新增制造厂商
                    manufacturerMapper.addManufacturers(manufacturerBean);
                    sample.zzcsId = String.valueOf(manufacturerBean.getId());
                    sample.zzcs = sample.respirator.zzcs;
                }else{
                    sample.zzcsId = sample.respirator.zzcsId;
                    sample.zzcs = sample.respirator.zzcs;
                }


                String sjrqstr = sample.respirator.sjri;


                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
                SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy.MM");
                //输出结果为
                String jyrqNianStr =   dateFormat.format(TimeUtil.parsex(sjrqstr));
                //输出结果为
                String jyrqYueStr =   dateFormat2.format(TimeUtil.parsex(sjrqstr));
                sample.jyrqNian = jyrqNianStr;
                sample.jyrqYue = jyrqYueStr;




                //-------修改了匹配气瓶的信息  对相应的报告的疲惫信息做更改start ------------//
                //先查询对应的报告有没有 (面罩)
                Report isReport =  reportDao.getReportBybsbh(sample.bsbh,1);
                //如果查询出来有报告
                if(null !=isReport){
                    //如果两个的匹配气瓶信息不一样
                    //if(!sample.respirator.qpbsh.equals(isReport.respirator.qpbsh)){
                    //将新的匹配气瓶 设置过去
                    isReport.respirator.qpbsh = sample.respirator.qpbsh;
                    reportDao.save(isReport);
                    //}
                }
                //-------修改了匹配气瓶的信息  对相应的报告的疲惫信息做更改end ------------//


                //计算上次检验日期
                List<Sample> samplesoo =   mSampleDao.getSample(1,sample.sbbh,"","");
                if(samplesoo.size()>0){
                    Sample sample122 = samplesoo.get(0);
                    if(!sample122.bsbh .equals(sample.bsbh)){
                        sample.respirator.scjyrq = sample122.respirator.sjri;
                    }
                }
                //设置旧品
//                sample.respirator.sfxp =0;
            }else if(null != sample.cylinders){
                //如果委托方Id为空就新建一条委托方的数据
                if( 0  == sample.cylinders.wtfId || "".equals(sample.cylinders.wtfId)){
                    CustomerBean customerBean = new CustomerBean();
                    customerBean.setEnterpriseName(sample.cylinders.wtf);
                    customerBean.setProvince(0);
                    customerBean.setCity(0);
                    customerBean.setBlock(0);
                    customerBean.setAddress("");
                    customerBean.setContacts("");
                    customerBean.setPhone("");
                    customerBean.setEmail("");
                    customerBean.setTelephone("");
                    customerBean.setFax("");
                    customerBean.setAddTime(TimeUtil.currentTimeMillis());
                    customerBean.setAddUser(String.valueOf(user.getUserId()));
                    customerBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    customerBean.setUpdateUser(String.valueOf(user.getUserId()));
                    int res = customerMapper.addCustomer(customerBean);
                    sample.wtfId =customerBean.getCustomerId();
                    sample.sjr = sample.cylinders.sjr;
                }else{
                    sample.wtfId = sample.cylinders.wtfId;
                    sample.sjr = sample.cylinders.sjr;
                    sample.sjrId = sample.cylinders.sjrId;
                }

                //如果制造厂商的id为空  就新增一条信息
                if(null ==sample.cylinders.zzcsId|| "".equals(sample.cylinders.zzcsId)){
                    ManufacturerBean manufacturerBean = new ManufacturerBean();
                    manufacturerBean.setName(sample.cylinders.zzcs);
                    manufacturerBean.setEnname("");
                    manufacturerBean.setAddress("");
                    long tt =TimeUtil.currentTimeMillis();
                    manufacturerBean.setAddTime(tt);
                    manufacturerBean.setAddUser(user.getUserId()+"");
                    manufacturerBean.setUpdateTime(tt);
                    manufacturerBean.setUpdateUser(user.getUserId()+"");
                    //新增制造厂商
                    manufacturerMapper.addManufacturers(manufacturerBean);
                    sample.zzcsId = String.valueOf(manufacturerBean.getId());
                    sample.zzcs = sample.cylinders.zzcs;
                }else{
                    sample.zzcsId = sample.cylinders.zzcsId;
                    sample.zzcs = sample.cylinders.zzcs;
                }

                String sjrqstr = sample.cylinders.sjri;
                SimpleDateFormat dateFormat4= new SimpleDateFormat("yyyy");
                SimpleDateFormat dateFormat5 = new SimpleDateFormat("yyyy.MM");
                //输出结果为
                String jyrqNianStr =   dateFormat4.format(TimeUtil.parsex(sjrqstr));
                //输出结果为
                String jyrqYueStr =   dateFormat5.format(TimeUtil.parsex(sjrqstr));
                sample.jyrqNian = jyrqNianStr;
                sample.jyrqYue = jyrqYueStr;

                //计算上次检验日期
                List<Sample> samplesoo =   mSampleDao.getSample(2,sample.sbbh,"","");
                if(samplesoo.size()>1){
                    Sample sample122 = samplesoo.get(1);
                    if(sample122.bsbh.equals(sample.bsbh)){
                        sample.cylinders.scjyrq = sample122.cylinders.sjri;
                    }
                }
            }
            // 保存数据
            // 取得是否存在旧的数据
            Sample oldData = mSampleDao.getSampleById(sample.bsbh);
            if (oldData != null) {
                sample.bhgyy = oldData.bhgyy;
                sample.sampleStatue = oldData.sampleStatue;
                sample.rwdbh= oldData.rwdbh;
                sample.jsrqLong = oldData.jsrqLong;
                //如果是面罩
                if(oldData.type ==Sample.YP_TYPE_HXQ){
                    sample.respirator.zjqmx = oldData.respirator.zjqmx;
                    sample.respirator.bjsq = oldData.respirator.bjsq;
//                    sample.respirator.sfxp = oldData.respirator.sfxp;
//                    sample.respirator.xjpType = oldData.respirator.xjpType;
                    sample.respirator.zsjyrq = oldData.respirator.zsjyrq;
                }else{
                    sample.cylinders.zsjyrq = oldData.cylinders.zsjyrq;
                }
            }else{
                sample.sampleStatue = 2;  // 没有已接收状态了  来就是检测中
                sample.bhgyy ="";
                sample.jsrqLong =0;

            }
            // 设置一次数据编号
            sample.bh = sample.bsbh;//BHUtil.getBHID(sample.type, sample.bsbh);
            long time = TimeUtil.getCurrentTimeMillis();
            sample.setAddUser(user.getUserId() + "");
            sample.setAddTime(time);
            sample.setUpdateUser(user.getUserId() + "");
            sample.setUpdateTime(time);
            sample.setSysStatus(BaseBean.SYS_STATUS_OK);


            if(sample.type ==1){
                //如果没有分配任务
                if(null ==sample.respirator.jcrId || "".equals(sample.respirator.jcrId)){
                    //查询任务列表
                    WorkBean workBean = workMapper.getWorkListByBsbh(sample.bsbh);
                    if(null !=workBean){
                        if(workBean.getJyyId() != user.getUserId()){
                            ret.setCode(ResultMsg.ERROR);
                            ret.setMsg("不是您的任务,请查看标识编号是否输入正确！");
                            return ret;
                        }
                        sample.respirator.jcrId = workBean.getJyyId()+"";
                        sample.respirator.jcr = workBean.getJyy();
                        sample.rwdbh = workBean.getRwdbh();
                        sample.jsrqLong = workBean.getJsrqLong();
                        //并更新工作表的 状态和 设备编号
                        workMapper.upfateWorkBhOrTp(sample.bsbh,sample.sbbh,3);
                    }
                }
            }else{
                //如果没有分配任务
                if(null ==sample.cylinders.jcrId || "".equals(sample.cylinders.jcrId)){
                    //查询任务列表
                    WorkBean workBean = workMapper.getWorkListByBsbh(sample.bsbh);
                    if(null !=workBean){
                        if(workBean.getJyyId() != user.getUserId()){
                            ret.setCode(ResultMsg.ERROR);
                            ret.setMsg("不是您的任务,请查看标识编号是否输入正确！");
                            return ret;
                        }
                        sample.cylinders.jcrId =workBean.getJyyId()+"";
                        sample.cylinders.jcr = workBean.getJyy();
                        sample.rwdbh = workBean.getRwdbh();
                        sample.jsrqLong = workBean.getJsrqLong();
                        //并更新工作表的 状态和 设备编号
                        workMapper.upfateWorkBhOrTp(sample.bsbh,sample.sbbh,3);
                    }
                }
            }

            if(sample.type == Sample.YP_TYPE_HXQ){
                String pxzdStr = sample.bsbh.replace("DQFJ","");
                sample.pxzd = pxzdStr;
            }else{
                String pxzdStr = sample.bsbh.replace("YTQP","");
                sample.pxzd = pxzdStr;
            }

            mSampleDao.save(sample);
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("保存成功");

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //新增操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                if(sample.type == 1){
                    historyBean.setMessage("[" + user.getUserName() + "] 新增了编号为： [" + sample.bh + "] 的样品 [呼吸器]");
                    historyBean.setType(Opt.YPGL_YPDJ_XZYP_XZHXQ);
                }else{
                    historyBean.setMessage("[" + user.getUserName() + "] 新增了编号为： [" + sample.bh + "] 的样品 [复合气瓶]");
                    historyBean.setType(Opt.YPGL_YPDJ_XZYP_FHQP);
                }
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(sample.bh));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 更新
     * @param request
     * @param sampleJson
     * @return
     */
    public ResultMsg upfatePcSample(HttpServletRequest request,String sampleJson){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_SJYPDJ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            Sample sample = JSON.parseObject(sampleJson, Sample.class);
            // 数据检查
            if (StringUtil.isEmpty(sample.bh) || StringUtil.isEmpty(sample.bsbh) || StringUtil.isEmpty(sample.erweima)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据错误！");
                return ret;
            }



            if(null != sample.respirator){
                //如果委托方Id为空就新建一条委托方的数据
                if(0  ==sample.respirator.wtfId || "".equals(sample.respirator.wtfId)){
                    CustomerBean customerBean = new CustomerBean();
                    customerBean.setEnterpriseName(sample.respirator.wtf);
                    customerBean.setProvince(0);
                    customerBean.setCity(0);
                    customerBean.setBlock(0);
                    customerBean.setAddress("");
                    customerBean.setContacts("");
                    customerBean.setPhone("");
                    customerBean.setEmail("");
                    customerBean.setTelephone("");
                    customerBean.setFax("");
                    customerBean.setAddTime(TimeUtil.currentTimeMillis());
                    customerBean.setAddUser(String.valueOf(user.getUserId()));
                    customerBean.setUpdateTime(TimeUtil.currentTimeMillis());
                    customerBean.setUpdateUser(String.valueOf(user.getUserId()));
                    int res = customerMapper.addCustomer(customerBean);
                }
            }
            // 保存数据
            // 取得是否存在旧的数据
            // 保存数据
            Sample oldData = mSampleDao.getSampleByBH(sample.bh);
            if (oldData == null) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据错误！");
                return ret;
            }
//            if(oldData.getUpdateTime() > sample.getUpdateTime()) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("该数据已经被其他人更新了！");
//                return ret;
//            }
            long time = TimeUtil.getCurrentTimeMillis();
            sample.setUpdateUser(user.getUserId() + "");
            sample.setUpdateTime(time);
            sample.setSysStatus(BaseBean.SYS_STATUS_OK);
            mSampleDao.save(sample);
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("修改成功");

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //新增操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                if(sample.type == 1){
                    historyBean.setMessage("[" + user.getUserName() + "] 修改了编号为： [" + sample.bh + "] 的样品 [呼吸器]");
                    historyBean.setType(Opt.YPGL_YPDJ_XZYP_XGHXQ);
                }else{
                    historyBean.setMessage("[" + user.getUserName() + "] 修改了编号为： [" + sample.bh + "] 的样品 [复合气瓶]");
                    historyBean.setType(Opt.YPGL_YPDJ_XGYP_FHQP);
                }
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(sample.bh));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 分页查询样品
     * @param pageNum  页数
     * @param pageSize  每页条数
     * @param bsbh   标识编号
     * @param erweima  二维码
     * @param type  样品类型  1：呼吸器  2: 复合气瓶
     * @param sampleStatue    设备状态   1：已接受   2：检测中 3：检测不合格 4：合格 5：维修中 6:已废弃
     * @param wtfId  委托方id
     * @param s_sbbh  设备编号
     * @return
     */
    public ResultMsg getSampleListPage(HttpServletRequest request,Integer pageNum,Integer pageSize,String bsbh,
                                       String erweima,int type,int sampleStatue,int wtfId,int wtfIdChi,String s_sbbh,String zzcsId,String rwdbh,String jcrId){
        List<Sample> sampleList = new ArrayList<Sample>();
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_YPYL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            if (pageNum != null && pageSize != null) {
                pageNum = (pageNum - 1) * pageSize;
            }





            //分页查询数据
            List<Sample>  samples =  mSampleDao.getSampleListPage( pageNum, pageSize, bsbh, erweima, type, sampleStatue, wtfId, wtfIdChi,s_sbbh,zzcsId,rwdbh,jcrId);
            //查询总条数
            long  total = mSampleDao.getSampleListTotle(bsbh, erweima, type, sampleStatue, wtfId,wtfIdChi, s_sbbh,zzcsId,rwdbh,jcrId);
            RespPageBean bean = new RespPageBean();
            bean.setData(samples);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;


    };


    /**
     * 分页查询我的样品
     * @param pageNum  页数
     * @param pageSize  每页条数
     * @param bsbh   标识编号
     * @param erweima  二维码
     * @param type  样品类型  1：呼吸器  2: 复合气瓶
     * @param sampleStatue    设备状态   1：已接受   2：检测中 3：检测不合格 4：合格 5：维修中 6:已废弃
     * @param wtfId  委托方id
     * @param s_sbbh  设备编号
     * @return
     */
    public ResultMsg getSampleMeListPage(HttpServletRequest request,Integer pageNum,Integer pageSize,String bsbh,String erweima,int type,int sampleStatue,int wtfId,int wtfIdChi,String s_sbbh,String zzcsId,String rwdbh){
        List<Sample> sampleList = new ArrayList<Sample>();
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_YPYL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            if (pageNum != null && pageSize != null) {
                pageNum = (pageNum - 1) * pageSize;
            }

            String jcrId =  String.valueOf(user.getUserId());

            //分页查询数据
            List<Sample>  samples =  mSampleDao.getSampleMeListPage( pageNum, pageSize, bsbh, erweima, type, sampleStatue, wtfId,wtfIdChi ,s_sbbh,zzcsId, jcrId,rwdbh);
            //查询总条数
            long  total = mSampleDao.getSampleMeListTotle(bsbh, erweima, type, sampleStatue, wtfId,wtfIdChi, s_sbbh,zzcsId,jcrId,rwdbh);
            RespPageBean bean = new RespPageBean();
            bean.setData(samples);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;


    };



    /**
     *  补打二维码  查询列表 分页
     * @param request
     * @param pageNum
     * @param pageSize
     * @param bsbh
     * @param sbbh
     * @return
     */
    public ResultMsg getSampleListPdewm(HttpServletRequest request,Integer pageNum,Integer pageSize,Integer type,String bsbh,String sbbh,String jcrId){
        List<Sample> sampleList = new ArrayList<Sample>();
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);

            if (pageNum != null && pageSize != null) {
                pageNum = (pageNum - 1) * pageSize;
            }
            //分页查询数据
            List<Sample>  samples =  mSampleDao.getSampleListPdewm( pageNum, pageSize,type, bsbh, sbbh,jcrId);
            //查询总条数
            long  total = mSampleDao.getSampleListPdewmTotle(bsbh,type, sbbh,jcrId);
            RespPageBean bean = new RespPageBean();
            bean.setData(samples);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;


    };



    public ResultMsg getSampleListZt(HttpServletRequest request,Integer pageNum,Integer pageSize,int type,String bsbh,String qpbsh,String sbbh,String rwdbh){
        List<Sample> sampleList = new ArrayList<Sample>();
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);

            if (pageNum != null && pageSize != null) {
                pageNum = (pageNum - 1) * pageSize;
            }
            //分页查询数据
            List<Sample>  samples =  mSampleDao.getSampleListZt( pageNum, pageSize,type, bsbh,qpbsh, sbbh,rwdbh);
            //查询总条数
            long  total = mSampleDao.getSampleListZtTotle(bsbh,type,qpbsh, sbbh,rwdbh);
            RespPageBean bean = new RespPageBean();
            bean.setData(samples);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;


    };




    /**
     * 查询为分配的 任务的 样品
     * @param bsbh   标识编号
     * @param type  样品类型  1：呼吸器  2: 复合气瓶
     * @return
     */
    public ResultMsg getSampleListWorkAll(HttpServletRequest request,String bsbh,int type){
        List<Sample> sampleList = new ArrayList<Sample>();
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.ZYGL_ZYYL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            //查询所有数据
            List<Sample>  samples =  mSampleDao.getSampleListWorkAll( bsbh, type);
            ret.setData(samples);
            ret.setCode(ResultMsg.SUCESS);

        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;

    };


    /**
     * 分配任务
     * @param request
     * @return
     */
    public ResultMsg assignTasks(HttpServletRequest request,String [] bsbhArrar,String jcrUserId,String jcrStr) {
        List<Sample> sampleList = new ArrayList<Sample>();
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.ZYGL_ZYYL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            for(String bsbh:bsbhArrar){
                //
                Sample mSample =  mSampleDao.getPcSampleByBsbh(bsbh);
                if(mSample.type == 1){
                    mSample.respirator.jcrId = jcrUserId;
                    mSample.respirator.jcr =jcrStr;
                }else{
                    mSample.cylinders.jcrId = jcrUserId;
                    mSample.cylinders.jcr =jcrStr;
                }
                mSampleDao.save(mSample);
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("分配成功");
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    public ResultMsg  deleteSamp (HttpServletRequest request,String bh,String bsbh) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            long res = mSampleDao.deleteById(bh);
            if(res>0){
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");

                //添加操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "] 删除了标识编号为： [" + bsbh + "] 的样品信息");
                historyBean.setType(Opt.YPGL_YPYL_SCYP);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(bsbh);
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);


            }else{
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据异常");
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    public ResultMsg   updateZjqmxBjsq(HttpServletRequest request,String bh,String zjqmx,String bjsq){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            Sample ms= mSampleDao.getSampleByBH(bh);
            ms.respirator.zjqmx =zjqmx;
            ms.respirator.bjsq =bjsq;
            mSampleDao.save(ms);
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("操作成功");
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 添加 任务单号 和 减检验员
     * @param request
     * @param rwdbh
     * @param jcr
     * @param jcrId
     * @return
     */
    public ResultMsg   addRwdbhOrJyy(HttpServletRequest request,String bh,String rwdbh,String jcr,String jcrId){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            Sample ms= mSampleDao.getSampleByBH(bh);
            ms.rwdbh = rwdbh;
            if(ms.type == Sample.YP_TYPE_HXQ){
                ms.respirator.jcr = jcr;
                ms.respirator.jcrId = jcrId;
            }else{
                ms.cylinders.jcr = jcr;
                ms.cylinders.jcrId = jcrId;
            }
            mSampleDao.save(ms);
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("操作成功");
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }







}
